package cn.cpy.sms.login.service.impl;

import cn.cpy.sms.login.common.enumerator.ServiceCode;
import cn.cpy.sms.login.dao.cache.repository.IPassportCacheRepository;
import cn.cpy.sms.login.dao.persist.repository.IPassportRepository;
import cn.cpy.sms.login.exception.ServiceException;
import cn.cpy.sms.login.pojo.entity.User;
import cn.cpy.sms.login.pojo.param.UserLoginParam;
import cn.cpy.sms.login.pojo.vo.UserLoginVO;
import cn.cpy.sms.login.service.IPassportService;
import cn.cpy.sms.login.utils.SmsUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.UUID;

@Slf4j
@Service
public class PassportServiceImpl implements IPassportService {
    @Autowired
    SmsUtil smsUtil;
    @Autowired
    IPassportCacheRepository passportCacheRepository;
    @Autowired
    IPassportRepository passportRepository;

    @Override
    public void postSmsCode(String phone) {
        Integer codeInt = (int)(Math.random()*1000000);
        //生成随机验证码
        String code = String.format("%06d",codeInt);
        log.info("申请注册手机号:"+phone+", 生成验证码:"+code);
        //调用smsUtil工具发送验证码
        smsUtil.sendSMS(phone, code);
        //保存手机号和验证码到redis
        passportCacheRepository.savePhoneAndSmsCode(phone,code);
    }


    public void handleLogin(UserLoginParam loginParam){
        //1.检查用户是否已经登录
        boolean existsPhone = passportCacheRepository.existsUserVO(loginParam.getPhone());
        if(existsPhone) throw new ServiceException(ServiceCode.ERROR_CONFLICT,"用户已登录，请勿重复登录!");
        //2.从redis中处理对应手机号和验证码
        passportCacheRepository.validPhoneAndSmsCode(loginParam);

        //3.假如手机号和验证码通过，数据库查询用户信息
        UserLoginVO userLoginVO = passportRepository.getUserByMobile(loginParam.getPhone());
        //3.1 假如用户已存在，查询用户状态已禁用
        if(userLoginVO!=null && userLoginVO.getEnable()==0) throw new ServiceException(ServiceCode.ERROR_UNAUTHORIZED_DISABLED,"用户已被禁用!");
        //3.2 假如用户未存在，插入用户
        if(userLoginVO==null){
            User user = new User();
            UUID uuid = UUID.randomUUID();
            String id = uuid.toString().substring(0,24);
            user.setId(id);
            user.setNickname("");
            user.setImoocNum("");
            user.setFace("");
            user.setBirthday(LocalDateTime.now());
            user.setDescription("");

            user.setCanImoocNumBeUpdated(1);
            user.setMobile(loginParam.getPhone());
            user.setSex(1);
            user.setEnable(1);
            passportRepository.insertUser(user);
            userLoginVO = passportRepository.getUserByMobile(loginParam.getPhone());
        }
        //3.3 存入redis中
        passportCacheRepository.saveUserVO(userLoginVO);
        //登录成功
    }

    @Override
    public void logout(String phone) {
        passportCacheRepository.removeUser(phone);
    }
}
